﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Net.Browser;
using VAdvantage.DataBase;
using VAdvantage.Logging;
using System.Runtime.Serialization;

namespace VAdvantage
{
    public partial class App : Application
    {
        public Grid mainUI = new Grid();

        public virtual void OnStart()
        {

        }

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        /// <summary>
        /// Goes to page.
        /// </summary>
        /// <param name="myNextPage">My next page.</param>
        public void GoToPage(UIElement page)
        {
            App app = (App)Application.Current;

            MainPage child = app.mainUI.Children[0] as MainPage;

            app.mainUI.Children.Clear();
            //child.desktop = null;
            //child.LoginPage = null;
            child = null;
            ((MainPage)page).FontFamily = new System.Windows.Media.FontFamily("/VAdvantage;component/Fonts/Ubuntu-Regular.ttf#Ubuntu");
            app.mainUI.Children.Add(page);
        }


        public void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                if(!IsolatedStorageFile.IsEnabled)
                {
                    string msg = "Please tick CheckBox against 'Enable Application Storage' in last tab of Silverlight Configuration Popup "+ 
                                " OR set enable 'Remember History' option in Privacy Options of browser";
                    VAdvantage.LocalStorageManager.FirstInfo fI = new LocalStorageManager.FirstInfo(msg);
                    this.RootVisual = fI;
                    //MessageBox.Show ("Please enable Application storge or allow remenber restory");
                    return;
                }
                IsolatedStorageFile file =
                        IsolatedStorageFile.GetUserStoreForApplication();
                file = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error =>"+ex.Message);
                return;
            }
            
            VLogMgt.Initialize(true);
            VLogMgt.AddHandler(VLogFile.Get(true, Ini.FindHome(), true));

            IDictionary<String, String> initParams = new Dictionary<string,string>();

            // When running outside the browser, retrieve initParams from isolated storage.
            if (Application.Current.IsRunningOutOfBrowser)
            {
              
                try
                {
                    using (IsolatedStorageFile file =
                        IsolatedStorageFile.GetUserStoreForApplication())
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(
                        "initParams.txt", System.IO.FileMode.Open, file))
                    {
                        // The serializer requires a reference to System.Runtime.Serialization.dll.
                        DataContractSerializer serializer =
                            new DataContractSerializer(typeof(Dictionary<String, String>));
                        initParams = (Dictionary<String, String>)serializer.ReadObject(stream);
                    }
                }

                catch( System.Exception ex)
                {
                    initParams = new Dictionary<String, string>();
                    //initParams[LocalStorageManager.StorageManager.UPDATEVERSION] = "0";
                }
               
            }
            // Otherwise, save initParams to isolated storage.
            else
            {
                initParams = e.InitParams;
                initParams["#ApplicationURL"] = System.Windows.Browser.HtmlPage.Document.DocumentUri.ToString(); 
                using (IsolatedStorageFile file =
                    IsolatedStorageFile.GetUserStoreForApplication())
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(
                    "initParams.txt", System.IO.FileMode.Create, file))
                {
                    DataContractSerializer serializer =
                        new DataContractSerializer(typeof(Dictionary<string, string>));
                    serializer.WriteObject(stream, initParams);
                }
            }

          
            bool b = Ini.LoadProperties();
           
            //bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            //bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);

            //Utility.AEnv.UpdateVersion = "0";
            //if (initParams.Keys.Contains(LocalStorageManager.StorageManager.UPDATEVERSION))
            //{
            //    IsolatedStorageSettings.ApplicationSettings[LocalStorageManager.StorageManager.UPDATEVERSION] = initParams[LocalStorageManager.StorageManager.UPDATEVERSION];
            //}
            //else
            //{
            //    IsolatedStorageSettings.ApplicationSettings[LocalStorageManager.StorageManager.UPDATEVERSION] = "-1";
            //}

            //if (initParams.Keys.Contains("SC_ImageCount"))
            //{
            //    try
            //    {
            //        GlobalVariable.SC_IMAGECOUNT = Convert.ToInt32(initParams["SC_ImageCount"]);
            //    }
            //    catch
            //    {

            //    }
            //}

            if (initParams.Keys.Contains("#ApplicationURL"))
            {
                IsolatedStorageSettings.ApplicationSettings["#ApplicationURL"] = initParams["#ApplicationURL"];
            }


            if (initParams.Keys.Contains("User"))
            {
            //    try
            //    {
                    GlobalVariable.UserName = initParams["User"];
            //    }
            //    catch
            //    {
            //    }
            }

            if(initParams.Keys.Contains("Pwd"))
            {
                GlobalVariable.Pwd = initParams["Pwd"];
            }
           // IsolatedStorageSettings.ApplicationSettings[LocalStorageManager.StorageManager.ISALL_SAVED] = "N";
            // new VAdvantage.Framework.VLogin();
         
            this.RootVisual = mainUI;
            MainPage mp = new MainPage();
            mp.FontFamily = new System.Windows.Media.FontFamily("/VAdvantage;component/Fonts/Ubuntu-Regular.ttf#Ubuntu");
            mainUI.Children.Add(mp);
            OnStart();
          
            //this.RootVisual = new VAdvantage.Framework.UserPreference();
        }

        public void Application_Exit(object sender, EventArgs e)
        {
            mainUI = null;
        }

        public void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        public void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }

        public static void StartUp(IDictionary<string, string> iDictionary)
        {
            bool b = Ini.LoadProperties();

            //bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            //bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);

            //Utility.AEnv.UpdateVersion = "0";
            //if (iDictionary.Keys.Contains(LocalStorageManager.StorageManager.UPDATEVERSION))
            //{
            //    IsolatedStorageSettings.ApplicationSettings[LocalStorageManager.StorageManager.UPDATEVERSION] = iDictionary[LocalStorageManager.StorageManager.UPDATEVERSION];
            //}
            //else
            //{
            //    IsolatedStorageSettings.ApplicationSettings[LocalStorageManager.StorageManager.UPDATEVERSION] = "-1";
            //}
            //IsolatedStorageSettings.ApplicationSettings[LocalStorageManager.StorageManager.ISALL_SAVED] = "N";
        }
    }
}
